/**
 * <rect x="30" y="30" rx="12" ry="12" width="350" height="150" style="fill:rgb(0,0,255);stroke-width:1;stroke:black"/>
 */

package cn.gotom.svg;

import android.graphics.Canvas;
import android.graphics.RectF;
import cn.gotom.svg.xml.StyleAttribute;

/**
 * @author 裴绍国
 * @author <a href="mailto:peixere@gmail.com">裴绍国</a>
 */
public class Rect extends RenderableElement
{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	float x = 0f;
	float y = 0f;
	float width = 0f;
	float height = 0f;
	float rx = 0f;
	float ry = 0f;

	private RectF rect;

	public Rect()
	{
	}

	protected void build() throws SVGException
	{
		super.build();
		StyleAttribute sty = new StyleAttribute();
		if (getAttribute(sty.setName("x")))
			x = sty.getFloatValueWithUnits();
		if (getAttribute(sty.setName("y")))
			y = sty.getFloatValueWithUnits();
		if (getAttribute(sty.setName("width")))
			width = sty.getFloatValueWithUnits();
		if (getAttribute(sty.setName("height")))
			height = sty.getFloatValueWithUnits();
		boolean rxSet = false;
		if (getAttribute(sty.setName("rx")))
		{
			rx = sty.getFloatValueWithUnits();
			rxSet = true;
		}
		boolean rySet = false;
		if (getAttribute(sty.setName("ry")))
		{
			ry = sty.getFloatValueWithUnits();
			rySet = true;
		}
		if (!rxSet)
			rx = ry;
		if (!rySet)
			ry = rx;
		rect = new RectF(x, y, x + width, y + height);
	}

	public void render(Canvas canvas) throws SVGException
	{
		if (this.visible())
		{
			beginLayer(canvas);
			renderRect(canvas);
			finishLayer(canvas);
		}
	}

	private void renderRect(Canvas canvas)
	{
		doFillPaint();
		if (rx > 0 || ry > 0)
		{
			canvas.drawRoundRect(rect, rx, ry, paint);
		}
		else
		{
			canvas.drawRect(rect, paint);
		}
		if (this.doStrokePaint())
		{
			if (rx > 0 || ry > 0)
			{
				canvas.drawRoundRect(rect, rx, ry, paint);
			}
			else
			{
				canvas.drawRect(rect, paint);
			}
		}
	}

	public RectF getBoundingBox()
	{
		return boundsToParent(includeStrokeInBounds(rect));
	}
}
